/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.zavakid.scala.exercise.chapter9

import scala.io.Source
import java.io.File

/**
 * @author zavakid 2013-6-11 下午4:02:39
 * @since 1.0
 */
object Main9 extends App {

  // 1
  def no1(filePath: String): Array[String] = {
    val source = Source.fromFile(filePath)
    source.getLines.toArray.reverse
  }

  // 2
  def no2(filePath: String): Array[String] = {
    val lines: Array[String] = Source.fromFile(filePath).getLines.toArray
    lines.map(_.replace("\t", "  "))
  }

  // 3
  def no3(filePath: String): Array[String] = {
    Source.fromFile(filePath).mkString.split("\\s+").filter(_.length > 12)
  }

  //4
  def no4(filePath: String) = {
    Source.fromFile(filePath).mkString.split("\\s+") filter { s: String =>
      try {
        s.toDouble
        true
      } catch {
        case _: Exception => false
      }
    } map {
      _.toDouble
    }
  }

  // 5 ignore

  // 6
  def no6(filePath: String) {
    val regex = "\"".r
    Source.fromFile(filePath).getLines.filter(!regex.findFirstMatchIn(_).isEmpty).foreach(println _)
  }

  //7
  def no7(filePath: String) {
    val regex = """d+"""".r
    Source.fromFile(filePath).mkString.split("\\s+").filter(!regex.findFirstMatchIn(_).isEmpty).foreach(println _)
  }

  // 8
  def no8() {
    val regex = """<img\s+src="([^"]+)"""".r
    val content = Source.fromURL("http://news.baidu.com/", "GBK").mkString
    println(content)
    for (regex(imgSrc) <- regex.findAllIn(content)) {
      println(imgSrc)
    }
  }

  // 9
  def no9(file: File): Int = {
    var num = 0
    file.listFiles() foreach {
      f: File =>
        if (f.isDirectory()) num += no9(f)
        else if (f.getPath().endsWith(".scala")) num += 1
    }
    num
  }

}